package com.socialuni.sdk.manage;

import com.socialuni.sdk.constant.platform.PlatformType;
import com.socialuni.sdk.exception.UniSdkException;
import com.socialuni.sdk.model.DO.user.AccountDO;
import com.socialuni.sdk.model.DO.user.UserDO;
import com.socialuni.sdk.model.ProviderLoginQO;
import com.socialuni.sdk.model.UniUnionIdRO;
import com.socialuni.sdk.repository.AccountRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CommonUserAccountDOCreate {
    @Resource
    AccountRepository accountRepository;

    public AccountDO create(UserDO user, ProviderLoginQO loginQO, UniUnionIdRO uniUnionIdRO) {
        AccountDO accountDO = new AccountDO();
        accountDO.setUserId(user.getId());
        accountDO.setPlatform(loginQO.getPlatform());
        accountDO.setProvider(loginQO.getProvider());
        String openId = uniUnionIdRO.getOpenid();
        if (StringUtils.isEmpty(openId)) {
            throw new UniSdkException("openId为空");
        }
        if (PlatformType.mp.equals(loginQO.getPlatform())) {
            //相同都为unionid
            accountDO.setMpOpenId(openId);
            accountDO.setAppOpenId("");
        } else {
            accountDO.setAppOpenId(openId);
            accountDO.setMpOpenId("");
        }
        if (StringUtils.isEmpty(uniUnionIdRO.getUnionid())) {
            accountDO.setUnionId("");
        } else {
            accountDO.setUnionId(uniUnionIdRO.getUnionid());
        }
        accountDO.setSessionKey(uniUnionIdRO.getSession_key());
        accountRepository.save(accountDO);
        return accountDO;
    }
}
